package org.nicholasjones.radiocontroller.web.data;


import org.apache.log4j.Logger;
import org.hsqldb.Server;
import org.hsqldb.persist.HsqlProperties;
import org.hsqldb.server.ServerAcl;
import org.springframework.context.SmartLifecycle;

import java.io.IOException;
import java.util.Properties;

public class Database implements SmartLifecycle {

    private static final Logger LOG = Logger.getLogger(Database.class);
    private HsqlProperties properties;
    private Server server;
    private boolean running = false;

    public Database(Properties props) {
        properties = new HsqlProperties(props);
    }

    /**
     * Determines if the database server is running.
     * @return true if the database is running.
     */
    @Override
    public boolean isRunning() {
        if(server != null) {
            server.checkRunning(running);
        }
        return running;
    }

    /**
     * Start the database.
     */
    @Override
    public void start() {
        if(server == null) {
            LOG.info("Starting HSQL server...");
            server = new Server();
            try {
                server.setProperties(properties);
                server.start();
                running = true;
            } catch(ServerAcl.AclFormatException afe) {
                LOG.error("Error starting HSQL server.", afe);
            }
            catch (IOException e) {
                LOG.error("Error starting HSQL server.", e);
            }
        }
    }

    /**
     * Stop the database.
     */
    @Override
    public void stop() {
        LOG.info("Stopping HSQL server...");
        if(server != null) {
            server.stop();
            running = false;
        }
    }

    @Override
    public int getPhase() {
        return 0;
    }

    @Override
    public boolean isAutoStartup() {
        return true;
    }

    @Override
    public void stop(Runnable runnable) {
        stop();
        runnable.run();
    }
}
